package com.ujiuye.filter;

import com.ujiuye.entity.UserInfo;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")  // 登录过滤器
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 向下类型强转
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        // 获取请求路径
        String uri = req.getRequestURI();
        // 截取最终的简化的请求路径
        String uriPath = uri.substring(uri.lastIndexOf("/") + 1);
        // 判断哪些请求不需要登录校验，如：登录页面，登录请求，注册页面，注册请求
        if ("register.html".equals(uriPath)||"register".equals(uriPath)
                ||"login.jsp".equals(uriPath)||"login".equals(uriPath)){
                // 直接放行
            filterChain.doFilter(req,resp);
        }else {
            // 需要进行登录安全校验
            HttpSession session = req.getSession();
            UserInfo user = (UserInfo) session.getAttribute("userInfo");
            if (user!=null){
                // 登陆成功
                filterChain.doFilter(req,resp);
            }else {
                // 去登陆
                resp.sendRedirect("login.jsp");
            }
        }


    }

    @Override
    public void destroy() {

    }
}
